<template>
  <a-spin
    :loading="loading"
    :size="35"
    class="w-[100%]"
    tip="正在处理, 请稍候..."
  >
    <a-space direction="vertical" fill size="medium">
      <!-- 基本信息 -->
      <a-descriptions :column="2" size="medium" bordered>
        <a-descriptions-item label="申请名称">
          {{ detailData.purchaseApplicationName || "-" }}
        </a-descriptions-item>
        <a-descriptions-item label="申请编号">
          {{ detailData.purchaseApplicationCode || "-" }}
        </a-descriptions-item>
        <a-descriptions-item label="申请时间">
          {{ detailData.applicationTime || "-" }}
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">
          {{ detailData.createTime || "-" }}
        </a-descriptions-item>
        <a-descriptions-item label="申请状态">
          <a-tag :color="getStatusColor(detailData.purchaseApplicationStatus)">
            {{ getStatusText(detailData.purchaseApplicationStatus) }}
          </a-tag>
        </a-descriptions-item>
      </a-descriptions>

      <!-- 项目列表 -->
      <div
        v-if="
          detailData.projectItemList && detailData.projectItemList.length > 0
        "
      >
        <a-divider orientation="left">项目列表</a-divider>
        <div
          v-for="(project, index) in detailData.projectItemList"
          :key="index"
        >
          <a-card class="mb-4">
            <a-descriptions :column="3" size="small" bordered>
              <a-descriptions-item label="项目名称">
                {{ project.projectName || "-" }}
              </a-descriptions-item>
              <a-descriptions-item label="项目编号">
                {{ project.projectCode || "-" }}
              </a-descriptions-item>
              <a-descriptions-item label="项目指标(亩)">
                {{ project.projectIndex || "-" }}
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
        </div>
      </div>

      <!-- 镇项目列表 -->
      <div v-if="detailData.townItemList && detailData.townItemList.length > 0">
        <a-divider orientation="left">镇项目列表</a-divider>
        <div v-for="(town, index) in detailData.townItemList" :key="index">
          <a-card class="mb-4">
            <a-descriptions :column="2" size="small" bordered>
              <a-descriptions-item label="镇街名称">
                {{ town.townName || "-" }}
              </a-descriptions-item>
              <a-descriptions-item label="购买亩数">
                {{ town.townIndex || "-" }}
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
        </div>
      </div>

      <!-- 确认函 -->
      <div v-if="confirmationFiles && confirmationFiles.length > 0">
        <a-divider orientation="left">确认函</a-divider>
        <a-card>
          <a-list :data="confirmationFiles" :bordered="false">
            <template #item="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #avatar>
                    <icon-file-pdf
                      v-if="item.file.fileType.includes('pdf')"
                      :size="24"
                    />
                    <icon-file v-else :size="24" />
                  </template>
                  <template #title>
                    {{ item.file.fileName }}
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-button
                    type="text"
                    size="small"
                    @click="downloadFile(item.file)"
                  >
                    <template #icon><icon-download /></template>
                    下载
                  </a-button>
                  <a-button
                    type="text"
                    size="small"
                    @click="previewFile(item.file)"
                  >
                    <template #icon><icon-eye /></template>
                    预览
                  </a-button>
                </template>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </div>

      <!-- 附件材料 -->
      <div v-if="attachmentFiles && attachmentFiles.length > 0">
        <a-divider orientation="left">附件材料</a-divider>
        <a-card>
          <a-list :data="attachmentFiles" :bordered="false">
            <template #item="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #avatar>
                    <icon-file-pdf
                      v-if="item.file.fileType.includes('pdf')"
                      :size="24"
                    />
                    <icon-file-image
                      v-else-if="item.file.fileType.includes('image')"
                      :size="24"
                    />
                    <icon-file v-else :size="24" />
                  </template>
                  <template #title>
                    {{ item.file.fileName }}
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-button
                    type="text"
                    size="small"
                    @click="downloadFile(item.file)"
                  >
                    <template #icon><icon-download /></template>
                    下载
                  </a-button>
                  <a-button
                    type="text"
                    size="small"
                    @click="previewFile(item.file)"
                  >
                    <template #icon><icon-eye /></template>
                    预览
                  </a-button>
                </template>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </div>

      <!-- 审批记录 -->
      <div
        v-if="
          detailData.approvalRecords && detailData.approvalRecords.length > 0
        "
      >
        <a-divider orientation="left">审批记录</a-divider>
        <a-timeline>
          <a-timeline-item
            v-for="(record, index) in detailData.approvalRecords"
            :key="index"
            :dot-color="getApprovalStatusColor(record.status)"
          >
            <template #dot>
              <icon-check-circle v-if="record.status === 'approved'" />
              <icon-close-circle v-else-if="record.status === 'rejected'" />
              <icon-clock-circle v-else />
            </template>
            <div>
              <div class="flex justify-between items-center mb-2">
                <span class="font-medium">{{
                  getApprovalActionText(record.action)
                }}</span>
                <span class="text-gray-500 text-sm">{{
                  record.createTime
                }}</span>
              </div>
              <div class="text-gray-600 text-sm mb-1">
                操作人: {{ record.operatorName }}
              </div>
              <div
                v-if="record.comment"
                class="bg-gray-50 p-2 rounded text-sm border-l-2 border-blue-500"
              >
                备注: {{ record.comment }}
              </div>
              <div
                v-if="record.confirmationFile"
                class="mt-2 p-2 bg-blue-50 rounded border-l-2 border-blue-400"
              >
                <div class="font-medium text-sm mb-1">确认函:</div>
                <a-link :href="record.confirmationFile.fileUrl" target="_blank">
                  <icon-file class="mr-1" />
                  {{ record.confirmationFile.fileName }}
                </a-link>
              </div>
            </div>
          </a-timeline-item>
        </a-timeline>
      </div>
    </a-space>
  </a-spin>
</template>

<script setup>
import {
  computed,
  defineEmits,
  defineProps,
  getCurrentInstance,
  onMounted,
  ref,
  watch,
} from "vue";
import { Message } from "@arco-design/web-vue";
import {
  IconArrowLeft,
  IconFile,
  IconFilePdf,
  IconFileImage,
  IconDownload,
  IconEye,
  IconCheckCircle,
  IconCloseCircle,
  IconClockCircle,
} from "@arco-design/web-vue/es/icon";
import { getPurchaseApplicationByPurchaseApplicationIdApi } from "~/api/lindi/purchaseApplication.js";

// 定义props
const props = defineProps({
  params: {
    type: Object,
    default: () => ({}),
  },
});

// 定义事件
const emit = defineEmits(["cancel"]);

// 全局实例
const { proxy } = getCurrentInstance();

// 字典数据
const dicts = proxy.LoadDicts([
  proxy.DICT.lindiProjectType,
  proxy.DICT.lindiPurchaseApplicationStatus,
]);

// 加载状态
const loading = ref(false);

// 详情数据
const detailData = ref({
  purchaseApplicationId: "",
  purchaseApplicationName: "",
  purchaseApplicationCode: "",
  applicationTime: "",
  createTime: "",
  updateTime: "",
  purchaseApplicationStatus: "",
  enterpriseName: "",
  reason: "",
  projectItemList: [],
  townItemList: [],
  fileList: [],
  approvalRecords: [],
});

// 确认函文件列表
const confirmationFiles = computed(() => {
  return (
    detailData.value.fileList?.filter((file) => file.fileType === "0") || []
  );
});

// 附件文件列表
const attachmentFiles = computed(() => {
  return (
    detailData.value.fileList?.filter((file) => file.fileType === "1") || []
  );
});

// 获取状态颜色
const getStatusColor = (status) => {
  if (!status || !dicts[proxy.DICT.lindiPurchaseApplicationStatus]) {
    return "gray";
  }
  const dict = dicts[proxy.DICT.lindiPurchaseApplicationStatus].find(
    (d) => String(d.dictKey) === String(status)
  );
  return dict?.dictClass || "gray";
};

// 获取状态文本
const getStatusText = (status) => {
  if (!status || !dicts[proxy.DICT.lindiPurchaseApplicationStatus]) {
    return "未知状态";
  }
  const dict = dicts[proxy.DICT.lindiPurchaseApplicationStatus].find(
    (d) => String(d.dictKey) === String(status)
  );
  return dict ? dict.dictValue : "未知状态";
};

// 获取项目类型文本
const getProjectTypeText = (projectType) => {
  const typeDict = dicts[proxy.DICT.lindiProjectType] || [];
  const typeItem = typeDict.find((item) => item.dictKey === projectType);
  return typeItem ? typeItem.dictValue : projectType || "未知类型";
};

// 获取审批状态颜色
const getApprovalStatusColor = (status) => {
  const colors = {
    approved: "#00b42a",
    rejected: "#f53f3f",
    pending: "#ff7d00",
  };
  return colors[status] || "#86909c";
};

// 获取审批操作文本
const getApprovalActionText = (action) => {
  const actions = {
    submit: "提交申请",
    approve: "审批通过",
    reject: "审批拒绝",
    return: "退回修改",
  };
  return actions[action] || action || "未知操作";
};

// 下载附件文件
const downloadFile = (file) => {
  if (file.fileUrl) {
    window.open(file.fileUrl, "_blank");
  } else {
    Message.error("文件下载链接不存在");
  }
};

// 预览附件文件
const previewFile = (file) => {
  if (file.fileUrl) {
    window.open(file.fileUrl, "_blank");
  } else {
    Message.error("文件预览链接不存在");
  }
};

// 获取购买申请详情
const getPurchaseApplicationDetail = () => {
  if (!props.params.purchaseApplicationId) {
    Message.error("缺少申请ID");
    return;
  }

  loading.value = true;

  getPurchaseApplicationByPurchaseApplicationIdApi(
    props.params.purchaseApplicationId
  )
    .then((response) => {
      const res = response;
      console.log("获取购买申请详情成功:", res);

      detailData.value = {
        purchaseApplicationId: res.purchaseApplicationId,
        purchaseApplicationName: res.purchaseApplicationName,
        purchaseApplicationCode: res.purchaseApplicationCode,
        applicationTime: res.applicationTime,
        createTime: res.createTime,
        updateTime: res.updateTime,
        purchaseApplicationStatus: res.purchaseApplicationStatus,
        enterpriseName: res.enterpriseName,
        reason: res.reason || "-",
        projectItemList: res.projectItemList || [],
        townItemList: res.townItemList || [],
        fileList: res.fileList || [],
        approvalRecords: res.approvalRecords || [],
      };

      // 文件数据已通过computed属性处理
    })
    .catch((error) => {
      console.error("获取购买申请详情失败:", error);
      Message.error("获取详情失败: " + (error.message || "网络错误"));
    })
    .finally(() => {
      loading.value = false;
    });
};

// 监听参数变化
watch(
  () => props.params,
  (newVal, oldVal) => {
    if (props.params.purchaseApplicationId) {
      getPurchaseApplicationDetail();
    }
  },
  { deep: true, immediate: true }
);

// 初始化
onMounted(() => {
  if (props.params.purchaseApplicationId) {
    getPurchaseApplicationDetail();
  }
});
</script>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.mb-2 {
  margin-bottom: 8px;
}

.mb-1 {
  margin-bottom: 4px;
}

.font-medium {
  font-weight: 500;
}

.text-gray-500 {
  color: #86909c;
}

.text-gray-600 {
  color: #4e5969;
}

.text-sm {
  font-size: 14px;
}

.bg-gray-50 {
  background-color: #f7f8fa;
}

.bg-blue-50 {
  background-color: #f0f9ff;
}

.p-2 {
  padding: 8px;
}

.rounded {
  border-radius: 4px;
}

.border-l-2 {
  border-left-width: 2px;
}

.border-blue-500 {
  border-left-color: #165dff;
}

.border-blue-400 {
  border-left-color: #1890ff;
}

.mt-2 {
  margin-top: 8px;
}

.mr-1 {
  margin-right: 4px;
}
</style>
